<template>
  <section
    class="OceVideo"
    ref="OceVideo"
    @mousemove="onMouse('enter')"
    @mouseleave="onMouse('leave')"
    @dblclick="fullScreenToggle"
    :class="{ 'full-screen': isFullScreen }"
  >
    <div
      class="video-img-show"
      v-if="(imageSrc && showImageSrc) || (errorImgSrc && showErrorImageSrc)"
    >
      <img
        :src="(showImageSrc && imageSrc) || (showErrorImageSrc && errorImgSrc)"
        class="video-img"
        :style="{ width: `${imgWidth}px`, height: `${imgHeight}px` }"
      />
    </div>
    <transition
      name="slide-fade"
      :duration="(noticeObj && noticeObj.duration) || 0"
    >
      <span
        :class="['video-notice']"
        v-if="noticeObj && noticeObj.text"
        :style="(noticeObj && noticeObj.style) || {}"
      >
        {{ (noticeObj && noticeObj.text) || '' }}
      </span>
    </transition>
    <!-- flvjs -->
    <div
      id="video"
      ref="video"
      class="video hideMenu"
      :class="{ 'display-scale': displayScale !== 'speed', canplay: canplay }"
      @contextmenu.prevent.capture.stop="onContextmenu"
      @click.capture.stop="onClick"
      v-if="videoType == 'flvjs'"
    ></div>

    <!-- xgPlayer -->
    <div
      id="video"
      ref="video"
      class="video hideMenu"
      @contextmenu.prevent.capture.stop="onContextmenu"
      v-else
    ></div>

    <!-- 控制条 -->
    <div
      class="controlColumn"
      :style="{ bottom, opacity, height: isLive ? '40px' : '60px' }"
      @mouseenter="isMouseControl = true"
      @mouseleave="isMouseControl = false"
      @dblclick.stop
    >
      <div class="progress" v-if="!isLive">
        <oce-progress
          style="height: 20px; width: 100%"
          :formatter="formatter"
          :option="progOption"
          :assistantNum.sync="assistantNum"
          :axisNum.sync="axisNum"
          @intercept="intercept"
        ></oce-progress>
      </div>
      <div class="fun">
        <div class="left">
          <!-- 暂停播放切换 -->
          <i
            :class="{
              iconfont: true,
              'icon-bofang': !isPlay,
              'icon-iconstop': isPlay,
            }"
            @click="playVideo(!isPlay)"
          />
          <!-- 视频当前播放时间点、视频总时长 -->
          <div class="text" v-if="!isLive" style="width: 140px">
            {{ timeFormat(axisNum) + ' / ' + timeFormat(duration || 0) }}
          </div>
          <!-- 直播流描述、速率 -->
          <div
            class="text"
            v-if="!hasAudio && isLive"
            :style="{ width: !isLive ? '80px' : '' }"
          >
            {{ infoText + speed + 'KB/s' }}
          </div>
        </div>

        <div class="right">
          <!-- 调整音量 -->
          <div class="volume">
            <div class="slider">
              <el-slider
                :value="volume"
                :show-tooltip="false"
                @input="adjustVolume"
                vertical
                height="80px"
              ></el-slider>
            </div>

            <i
              class="cursor-pointer"
              :class="{
                iconfont: true,
                'icon-shengyinkai': volume,
                'icon-jingyin': !volume,
              }"
              @click="mute"
              slot="reference"
            />
          </div>
          <!-- 倍速播放切换 -->
          <div class="times cursor-pointer" v-if="!isLive">
            <div class="select">
              <div
                v-for="(item, i) of timesList"
                :key="'times' + i"
                class="timesItem"
                :style="{ color: item.value == times.value ? '#1890FF' : '' }"
                @click="adjustTimes(item)"
              >
                {{ item.label }}
              </div>
            </div>

            <span>{{ times.value == 1 ? '倍速' : times.label }}</span>
          </div>
          <!-- 截图 -->
          <i class="iconfont icon-paizhao cursor-pointer" @click="screenshot" />

          <!-- 录制 -->
          <i
            :class="[
              'iconfont',
              isRecodeing ? 'icon-paizhao' : 'icon-paizhao',
              'cursor-pointer',
            ]"
            v-if="!isMP4"
            @click="toggleRecode"
          />

          <!-- 下载录像 -->
          <i
            class="el-icon-download cursor-pointer"
            v-if="!isLive && !isMP4"
            @click="downloadRecording"
          />
          <!-- 下载历史流录像 flv-->
          <i
            class="el-icon-download cursor-pointer"
            v-if="!isLive && !isMP4"
            @click="history_download"
          />
          <!-- 全屏切换 -->
          <i
            class="iconfont icon-quanping cursor-pointer"
            @click="fullScreenToggle"
          />
        </div>
      </div>
    </div>
    <span class="recode-time" v-if="isRecodeing">
      {{ formatSecondsSet() }}
    </span>
    <!-- <iframe name="frame" style="width: 0; height: 0" id="frame"></iframe> -->
  </section>
</template>

<script>
import { formatSeconds } from '@/components/common.js';
import OceProgress from '@/components/progress/src/progress.vue';
import dayjs from 'dayjs';
import flvjsMixin from './flvjsMixin';
export default {
  name: 'OceVideo',
  mixins: [flvjsMixin], //xgPlayerMixin -- 去除西瓜播放器 -- 不支持flv直播流
  data() {
    return {
      canplay: false, //是否可以播放
      player: null, //视频对象
      volume: 1, // 音量
      oldVolume: null, //历史音量 -- 用于静音恢复历史播放
      isPlay: true, //播放状态
      realIsPlay: true, // 用户操作播放状态
      bottom: '-40px', //控制条位置
      opacity: 0, //控制条透明度
      isFullScreen: false, //是否全屏
      isMouseControl: false,
      speed: 0, //视频传输速率
      noticeObj: {}, //通知弹窗对象
      noticeTime: null, //通知弹窗时间定时器
      imgWidth: 0, //图片宽
      imgHeight: 0, //图片高
      chunks: new Set(), //视频流
      mediaRecordObj: null, //视频流录制对象
      isRecodeing: false, //是否正在录制
      showImageSrc: false, //是否显示默认加载图
      showErrorImageSrc: false, //是否显示错误图片
      errorImgSrc: '', //默认错误图片
      segmentInternet: null,
      bolbListStart: [], //初始化视频流数据
      mediaObj: null, //视频对象
      mineType: 'video/webm', //默认录制视频类型
      bolbTime: 0,
      bolbList: [],
      bolbListLenStart: 0,
      progOption: {
        max: 100,
        dataInterception: true,
      },
      axisNum: 0,
      assistantNum: 0,
      duration: 0,
      isDrag: false,
      timesList: [
        //倍速列表
        {
          label: '16.0x',
          value: 16,
        },
        {
          label: '8.0x',
          value: 8,
        },
        {
          label: '4.0x',
          value: 4,
        },
        {
          label: '2.0x',
          value: 2,
        },
        // {
        //   label: "1.75x",
        //   value: 1.75,
        // },
        {
          label: '1.5x',
          value: 1.5,
        },
        // {
        //   label: "1.25x",
        //   value: 1.25,
        // },
        {
          label: '1.0x',
          value: 1,
        },
        // {
        //   label: "0.75x",
        //   value: 0.75,
        // },
        {
          label: '0.5x',
          value: 0.5,
        },
        // {
        //   label: "0.25x",
        //   value: 0.25,
        // },
      ],
      times: {
        //当前倍速
        label: '1.0x',
        value: 1,
      },
      videoType: 'flvjs', //视频类型
      connectTimeoutFlag: null, // 回连定时器标识
    };
  },
  computed: {
    isMP4() {
      let isMP4 = false;
      if (this.url.indexOf('.mp4') !== -1) {
        isMP4 = true;
      }
      return isMP4;
    },
  },
  props: {
    url: String, //视频地址
    fileName: String, //视频名称
    noticeTextObj: {
      type: Object,
      default: function (value) {
        return {
          text: '',
          duration: 1000,
          style: {
            fontSize: '14px',
            color: '#fff',
            background: 'rgba(0, 0, 0, 0.6)',
            borderRadius: '40px',
            top: '50%',
            left: '50%',
          },
        };
      },
    },
    id: [String, Number], //视频id
    displayScale: {
      //视频显示比例
      type: String,
      default: 'speed',
    },
    // 'flvjs' 'xgPlayer'
    playerType: {
      //视频类型
      type: String,
      default: 'flvjs',
    },
    realTime: String,
    infoText: {
      //视频描述 -- 车牌号
      type: String,
      default: () => {
        return '';
      },
    },
    hasAudio: {
      type: Boolean,
      default: false,
    },
    hasVideo: {
      type: Boolean,
      default: true,
    },
    isLive: {
      //是否直播流
      type: Boolean,
      default: true,
    },
    isRecord: {
      //是否历史流
      type: Boolean,
      default: false,
    },
    basisUrl: String,
    freeMediaUrl: Function,
    imageSrc: {
      type: String,
      default: () => {
        return '';
      },
    },
    errorImg: {
      //错误图片显示
      type: String,
      default: () => {
        return '';
      },
    },
  },
  watch: {
    volume: {
      //监听音量变化
      handler(val) {
        this.$emit('volumeChange', {
          id: this.id,
          volume: val,
        });
      },
    },
    url: {
      //监听视频url变化
      deep: true,
      handler: function (val) {
        // console.log(val, '是否切换视频源');
        if (!val) return;
        this.destroy();
        this.$nextTick(() => {
          this.playVideo(true);
        });
      },
    },
    //监听弹窗变化
    noticeTextObj: {
      deep: true,
      handler: function (newValue) {
        // console.log('文字变化', newValue);
        this.flvNotice(newValue);
      },
    },
  },
  components: { OceProgress },
  created() {
    this.errorImgSrc = this.errorImg || ''; //初始化默认图片
    if (this.player) this.destroy();
    // console.log("created");
    this.$nextTick(() => {
      this.player = this.initDPlayer(this.$refs.video, this.url);
      this.listenerVisibilitychange();
    });
    this.videoType = this.playerType.toString();

    // var ifm = document.getElementById('frame');

    // var subWeb = document?.frames
    //   ? document?.frames['frame']?.document
    //   : ifm?.contentDocument;
    // console.log(subWeb, 'subWeb');
    // subWeb.execCommand('SaveAs');
  },
  beforeDestroy() {
    this.destroy();
    this.freeMediaUrl && this.freeMediaUrl(this.basisUrl);
  },
  methods: {
    history_download() {
      // console.log('history_download', this.url);
      // var bolbListx = [];
      // var ws = new WebSocket(this.url); //下载flv格式，如果是直接下载，需要加个loading，如果是边播放边下载，需要考虑怎么解除只能单流播放限制
      // ws.onopen = function () {
      //   console.log('open');
      // };
      // ws.onmessage = function (e) {
      //   console.log(e.data, '监听数据');

      //   bolbListx.push(e.data);
      // };
      // ws.onclose = function (e) {
      //   console.log('close');
      //   alert('在这里增加loading');
      //   let blob = new Blob(bolbListx);

      //   let a = document.createElement('a');
      //   // let data = new Date().getTime();
      //   a.style.display = 'none';
      //   a.download = `test.flv`;
      //   const href = URL.createObjectURL(blob);
      //   a.href = href;
      //   a.click();
      //   alert('在这里增加解除loading');
      // };
      // ws.onerror = function (e) {
      //   console.log(error);
      // };
      if (!this.isRecord) {
        alert('非历史流，无法下载flv');
        return;
      }
      let bloblist = this.player.flvPlayer.getBolbList();
      console.log(bloblist);
      let blob = new Blob(bloblist);
      let a = document.createElement('a');
      let data = new Date().getTime();
      a.style.display = 'none';
      a.download = `${this.fileName || data}.flv`;
      const href = URL.createObjectURL(blob);
      a.href = href;
      a.click();
    },
    hideLoading() {
      //隐藏播放器中间loading
      const dplayer = document.querySelector('.dplayer-bezel');
      if (dplayer) {
        dplayer.style.display = 'none';
      }

      // dplayer-bezel
    },
    showLoading() {
      //显示播放器中间loading
      const dplayer = document.querySelector('.dplayer-bezel');
      if (dplayer) {
        dplayer.style.display = 'block';
      }
    },
    showErrorImg(errorImgSrc) {
      //显示错误图片
      if (errorImgSrc) {
        this.errorImgSrc = errorImgSrc;
      }
      this.showErrorImageSrc = true;
      this.hideLoading();
    },
    hideErrorImg() {
      //隐藏错误图片显示
      this.showErrorImageSrc = false;
      this.showLoading();
    },
    formatSecondsSet() {
      return formatSeconds(this.bolbTime);
    },
    //监听浏览器tab显隐
    listenerVisibilitychange() {
      const self = this;
      window.document.addEventListener('visibilitychange', function () {
        var isHidden = window.document.hidden;
        console.log(window.document.visibilityState, '浏览器状态', isHidden);
        if (self.isLive) {
          if (isHidden) {
            document.title = '隐藏';
          } else {
            // document.title = '显示';
            // 严谨一点先判断有没有缓存，然后把他时间设置到缓存前一点点时间所以-0.5，如果直接设置到.end(0)他还需要去加载内容才能流畅继续播放
            const buffered = self.player?.video?.buffered.end(0) - 0.5;
            const currentTime = self.player?.video?.currentTime;
            if (buffered - currentTime > 1) {
              self.player.video.currentTime = Math.floor(buffered);
            }
            // self.getFlvVideoMediaInfo();
          }
        }
      });
    },
    // 获取视频信息，含分辨率
    getFlvVideoMediaInfo() {
      const mediaInfo = this.player?.flvPlayer.mediaInfo;
      // const quality = this.player?.video.quality;
      if (this.$listeners?.getFlvVideoMediaInfo) {
        this.$emit('getFlvVideoMediaInfo', mediaInfo);
      }
      // console.log(mediaInfo, '视频信息', quality);
      return mediaInfo;
      // const statisticsInfo = this.player?.flvPlayer.statisticsInfo;
    },
    //设置视频通知
    flvNotice(newValue) {
      // this.player.notice(text, time);
      this.noticeObj = Object.assign(
        {},
        { ...this.noticeObj },
        { ...newValue }
      );
      const duration = newValue?.duration || 1000;
      if (this.noticeTime) {
        clearTimeout(this.noticeTime);
        this.noticeTime = null;
      }
      if (!newValue?.isLongDuration) {
        this.noticeTime = setTimeout(() => {
          this.noticeObj = Object.assign(
            {},
            { ...this.noticeObj },
            { text: '' }
          );
          clearTimeout(this.noticeTime);
          this.noticeTime = null;
        }, duration);
      }
    },
    clearNotice() {
      this.noticeObj = Object.assign(
        {},
        { ...this.noticeObj },
        {
          text: '',
          style: {
            //toast样式，默认
            fontSize: '14px',
            color: '#fff',
            background: 'rgba(0, 0, 0, 0.6)',
            borderRadius: '40px',
            top: '50%',
            left: '50%',
          },
        }
      );
      if (this.noticeTime) {
        clearTimeout(this.noticeTime);
        this.noticeTime = null;
      }
    },
    hideBaseImg() {
      this.showImageSrc = false;
    },
    doAppendSegmentsRecode() {
      // this.bolbList = [];
      if (this.segmentInternet) {
        clearInterval(this.segmentInternet);
        this.segmentInternet = null;
      }
      this.isRecodeing = true;
      this.bolbTime = 0;
      this.bolbTime++;
      let bolbList = this.player?.flvPlayer?.getBolbList();
      this.bolbListLenStart = bolbList?.length;

      this.segmentInternet = setInterval(() => {
        // const bolbSegment = this.player?.flvPlayer?.doAppendSegmentsRecode();
        // this.bolbList.push(bolbSegment);
        // const bolbList = this.player.flvPlayer.getBolbList();
        const bolbListNew = this.player.flvPlayer?._msectl?.bolbList;
        this.bolbList = [...this.bolbList, ...bolbListNew];
        // console.log(
        //   this.player.flvPlayer?._msectl,
        //   '视频流数据',
        //   this.player.flvPlayer?._msectl?._pendingSegments
        // );
        this.bolbTime++;
      }, 1000);
    },
    playerPause() {
      if (this.isRecodeing) {
        //如果暂停了就自动停止录制
        // this.doStopAppend(true);
        this.stopRecord();
      }
    },
    playerEnded() {
      if (this.isRecodeing) {
        //如果结束了就自动停止录制
        // this.doStopAppend(true);
        this.stopRecord();
      }
    },
    doStopAppend(quiet = false) {
      if (this.bolbTime <= 3 && !quiet) {
        const notice = {
          text: '请至少录制3s视频',
        };
        this.flvNotice(notice);
        return;
      }
      this.segmentInternet && clearInterval(this.segmentInternet);
      this.segmentInternet = null;
      this.isRecodeing = false;
      let bolbList = this.player?.flvPlayer?.getBolbList();
      const bolbListLenEnd = bolbList?.length + 1;
      // const timeLen = this.bolbTime;
      const bolbListNew = bolbList.slice(this.bolbListLenStart, bolbListLenEnd);

      let bolbTotal = [...this.bolbListStart, ...bolbListNew];
      if (this.bolbTime === 0) {
        bolbTotal = [...bolbListNew];
      }
      console.log(
        this.bolbTime,
        '计时秒数',
        this.bolbListStart,
        '初始化bolb数据',
        this.bolbListLenStart,
        '初始化截取节点',
        bolbListLenEnd,
        '停止截取节点',
        bolbList,
        '全部数据',
        bolbListNew,
        '截取数据加初始化数据',
        bolbTotal,
        '最后数据'
      );
      console.log(this.bolbList, '渐进数据');
      this.downloadBolb([...this.bolbList]);
    },
    // 下载录像
    downloadBolb(bolbList) {
      console.log('***********视频数据：', bolbList);
      let arr = [];
      bolbList.forEach((item) => {
        let temp = new Uint8Array(item);
        // arr = [...arr,...temp]
        arr.push(...temp);
      });
      // console.log('***********视频数据2：',arr)
      let uint8 = new Uint8Array(arr);
      // console.log(uint8);
      let arrayBuffer = uint8.buffer;
      let blob = new Blob([arrayBuffer]);
      // console.log(blob);
      let a = document.createElement('a');
      let data = new Date().getTime();
      // a.download = `导出视频${data}.mp4`
      a.style.display = 'none';
      a.download = `${this.fileName || data}.mp4`;
      const href = URL.createObjectURL(blob);
      a.href = href;
      a.click();
      // window.URL.revokeObjectURL(href);
    },
    // 下载录像 -- 全部
    downloadRecording() {
      let bolbList = this.player.flvPlayer.getBolbList();
      // console.log('***********视频数据：',bolbList)
      this.downloadBolb(bolbList);
    },
    // 调整倍速
    adjustTimes(t) {
      this.times = t;
      if (this.player?.video?.playbackRate)
        this.player.video.playbackRate = t.value;
    },
    // 手动修改时间轴
    intercept(time) {
      // console.log(time)
      if (time < this.assistantNum) {
        let t = Math.floor(time);
        this.player.video.currentTime = t;
        this.axisNum = t;
      } else {
        this.player.video.currentTime = this.assistantNum;
        this.axisNum = this.assistantNum;
      }
    },
    // 秒数转换为时分秒格式
    timeFormat(time) {
      if (time == Infinity) time = 0;
      let timeStr = '';
      let stringFormat = (i) => {
        i = Math.floor(i);
        return i < 10 ? `0${i}` : `${i}`;
      };
      let minuteTime = 0;
      let secondTime = 0;
      let hourTime = 0;
      if (time < 60) {
        timeStr = `00:${stringFormat(time)}`;
      } else if (time >= 60 && time < 3600) {
        minuteTime = parseInt(time / 60);
        secondTime = parseInt(time % 60);
        timeStr = `${stringFormat(minuteTime)}:${stringFormat(secondTime)}`;
      } else if (time >= 3600) {
        let _t = parseInt(time % 3600);
        hourTime = parseInt(time / 3600);
        minuteTime = parseInt(_t / 60);
        secondTime = parseInt(_t % 60);
        timeStr = `${stringFormat(hourTime)}:${stringFormat(
          minuteTime
        )}:${stringFormat(secondTime)}`;
      }
      return timeStr || '00:00';
    },
    // 进度条气泡格式
    formatter(val) {
      return this.timeFormat(val);
    },
    // 切换显示比例 speed 4:3 16:9 filling
    updateDisplayScale() {
      this[this.videoType + 'UpdateDisplayScale']();
    },
    // 自定义单击事件
    onClick(e) {
      this.$el.click();
      this.$emit('click', e);
    },
    // 自定义右键事件
    onContextmenu(event) {
      this.$emit('contextmenu', {
        event,
        player: this.player,
        isPlay: this.isPlay,
        id: this.id,
      });
    },
    // 销毁
    destroy() {
      this[this.videoType + 'Destroy']();
    },
    // 截图
    screenshot() {
      const canvas = document.createElement('canvas');
      canvas.width = this.player.video.videoWidth;
      canvas.height = this.player.video.videoHeight;
      canvas
        .getContext('2d')
        .drawImage(this.player.video, 0, 0, canvas.width, canvas.height);

      let dataURL;
      // let time = this.$ocean.moment().format('YYMMDDHHmm')
      let time = dayjs().format('YYMMDDHHmm');
      canvas.toBlob((blob) => {
        dataURL = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = dataURL;
        link.download = this.infoText + '-' + time + '.png';
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(dataURL);
      });
    },
    // 显示base64
    async showBase64() {
      const dataURL = await this.getBase64();
      const link = document.createElement('img');
      link.src = dataURL;
      document.body.appendChild(link);
    },
    // 获取base64数据
    async getBase64() {
      const canvas = document.createElement('canvas');
      canvas.width = this.player.video.videoWidth;
      canvas.height = this.player.video.videoHeight;
      return new Promise((resolve, reject) => {
        canvas
          .getContext('2d')
          .drawImage(this.player.video, 0, 0, canvas.width, canvas.height);
        canvas.toBlob((blob) => {
          this.blobToBase64(blob).then((res) => {
            // 转化后的base64
            // console.log('base64', res);
            resolve(res);
          });
        });
      });
    },
    // blob转base64
    blobToBase64(blob) {
      return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = (e) => {
          resolve(e.target.result);
        };
        // readAsDataURL
        fileReader.readAsDataURL(blob);
        fileReader.onerror = () => {
          reject(new Error('blobToBase64 error'));
        };
      });
    },
    // startRecodeMedia() {
    //   const canvas = document.createElement('canvas');
    //   canvas.width = this.player.video.videoWidth;
    //   canvas.height = this.player.video.videoHeight;
    //   canvas
    //     .getContext('2d')
    //     .drawImage(this.player.video, 0, 0, canvas.width, canvas.height);
    //   // let time = dayjs().format('YYMMDDHHmm');
    //   this.recodeInterval = setInterval(() => {
    //     canvas.toBlob((blob) => {
    //       this.chunks.add(blob);
    //     });
    //   }, 1000);
    //   setTimeout(() => {
    //     this.stopRecord();
    //   }, 10000);
    // },
    // 录制切换
    toggleRecode() {
      if (this.isRecodeing) {
        this.stopRecord();
      } else {
        this.startRecording();
      }
      // if (this.isRecodeing) {
      //   this.doStopAppend();
      // } else {
      //   this.doAppendSegmentsRecode();
      // }
    },
    // 开始录制
    startRecording() {
      this.adjustVolume(5);
      if (this.volume === 0) {
        const notice = {
          text: '静音状态，有可能录制失败',
          duration: 3000,
        };
        this.flvNotice(notice);
      }
      if (this.segmentInternet) {
        clearInterval(this.segmentInternet);
        this.segmentInternet = null;
      }
      this.bolbTime = -1;
      this.chunks.clear();
      this.segmentInternet = setInterval(() => {
        this.bolbTime++;
      }, 1000);
      this.isRecodeing = true;
      this.bolbTime++;
      console.log(this.player.video, 'this.player.video');
      const mediaStream = this.player.video.captureStream(30); // 获取媒体元素的媒体流对象
      console.log(mediaStream, '流媒体对象');

      var options = { audioBitsPerSecond : 128000, videoBitsPerSecond : 2500000,mimeType: 'video/webm',ignoreMutedMedia:true};

      let mediaRecordObj = new MediaRecorder(mediaStream, options);
      const isTypeSupported = MediaRecorder.isTypeSupported('video/webm;codecs=h264,opus'); // true or false
      if (isTypeSupported) {
        console.log('type video/webm;codecs=h264,opus is supported');
      //   this.mineType = 'video/mp4';
      }
      this.mineType = 'video/webm'
      this.mediaRecordObj = mediaRecordObj;
      // timeslice参数可选，表示以该持续时间切片媒体数据；
      mediaRecordObj.ondataavailable = (e) => {
        // 接收媒体流数据: Blob类型
        console.log(e.data, '数据');
        if (e.data.size > 0) {
          this.chunks.add(e.data);
        }
      };
      mediaRecordObj.start(1000); // 开始录屏
      // 返回当前MediaRecorder实例的工作状态，可选值有：inactive、recording和paused
      console.log(mediaRecordObj.state + ' start to recording .....');
    },
    pauseRecode() {
      //暂停录制
      this.mediaRecordObj && this.mediaRecordObj.pause();
    },
    resumeRecode() {
      //继续录制
      this.mediaRecordObj && this.mediaRecordObj.resume();
    },
    stopRecord() {
      this.mediaRecordObj.stop(); // 结束录屏
      // console.log(this.mediaRecordObj.mimeType, '媒体类型');
      // let mimeType = this.mediaRecordObj.mimeType;
      // const mimeTypeArray = mimeType?.split(';');
      const blobType = this.mineType;
      const blobTypeArray = blobType?.split('/');
      const streamType = blobTypeArray[1];
      // this.recodeInterval && clearInterval(this.recodeInterval);
      const videoBlob = new Blob(this.chunks, {
        type: this.mineType,
      });
      const videoUrl = window.URL.createObjectURL(videoBlob);
      this.download(videoUrl, streamType);
      this.segmentInternet && clearInterval(this.segmentInternet);
      this.segmentInternet = null;
      this.isRecodeing = false;
    },
    download(videoUrl, streamType = 'webm') {
      let time = dayjs().format('YYMMDDHHmm');
      var a = document.createElement('a');
      a.href = videoUrl;
      a.download = this.infoText + '-' + time + `.webm`;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
    },
    // 调整音量
    adjustVolume(vol) {
      // console.log(vol);
      if (!this.player || this.volume === vol) return;
      this.volume = vol;
      this.player.volume(this.volume / 100, true, false);
    },
    // 静音
    mute() {
      if (this.volume) {
        this.oldVolume = this.volume;
        this.volume = 0;
      } else {
        this.volume = this.oldVolume || 50;
        this.oldVolume = null;
      }
      this.player.volume(this.volume / 100, true, false);
    },
    // 切换播放状态播放
    playVideo(isPlay) {
      this[this.videoType + 'PlayVideo'](isPlay);
    },
    //暂停播放状态
    pauseVideo() {
      this[this.videoType + 'PauseVideo']();
    },
    // 重新播放
    replayVideo() {
      this[this.videoType + 'ReplayVideo']();
    },
    // 全屏切换
    fullScreenToggle() {
      if (this.isFullScreen) {
        if (document.exitFullscreen) {
          if (document.fullscreenElement) document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
        if (typeof cfs != 'undefined' && cfs) {
          cfs.call(el);
          console.log(cfs, el, '问题');
        }
        this.isFullScreen = false;
      } else {
        let el = document.documentElement;
        let rfs =
          el.requestFullScreen ||
          el.webkitRequestFullScreen ||
          el.mozRequestFullScreen ||
          el.msRequestFullscreen;
        if (typeof rfs != 'undefined' && rfs) {
          rfs.call(el);
        }
        // document.getElementsByClassName("app-main")[0].style.zIndex = "10";
        this.isFullScreen = true;
        window.onresize = () => {
          if (!this.$ocean.checkFull()) {
            this.isFullScreen = false;
            setTimeout(() => {
              this.updateDisplayScale();
            }, 50);
          }
        };
      }
      this.$nextTick(() => {
        this.updateDisplayScale();
      });
      // this.isFullScreen = !this.isFullScreen
    },
    // 监听鼠标
    onMouse(state) {
      switch (state) {
        case 'enter':
          this.bottom = 0;
          this.opacity = 1;
          // this.$ocean?.debounce(
          //   () => {
          //     if (this.isMouseControl) {
          //       this.onMouse('enter');
          //     } else {
          //       this.onMouse('leave');
          //     }
          //   },
          //   3000,
          //   false
          // );
          break;
        case 'leave':
          this.bottom = '-40px';
          this.opacity = 0;
          break;
      }
    },
    // 初始化视频
    initDPlayer(container, url) {
      this.$nextTick(() => {
        this.updateDisplayScale();
      });
      return this[this.videoType + 'InitDPlayer'](container, url); //执行混入方法
    },
  },
};
</script>

<style lang="scss" scoped>
.OceVideo {
  height: 100%;
  width: 100%;
  position: relative;
  overflow: hidden;
  background: black;
  .recode-time {
    position: absolute;
    right: 5%;
    bottom: 20%;
    // transform: translate(-50%, -50%);
    z-index: 999;
    background: rgba($color: #000000, $alpha: 0.6);
    color: #fff;
    border-radius: 40px;
    font-size: 14px;
    padding: 10px 10px;
  }
  .video-img-show {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    // font-size: 22px;
    // color: #fff;
    pointer-events: none;
    z-index: 5;
  }
  ::v-deep .dplayer-bezel {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    font-size: 22px;
    color: #fff;
    pointer-events: none;
    z-index: 10;
  }
  .video-notice {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
    background: rgba($color: #000000, $alpha: 0.6);
    color: #fff;
    border-radius: 40px;
    font-size: 14px;
    padding: 4px 10px;
  }
  .canplay {
    ::v-deep .diplayer-loading-icon {
      display: none !important;
    }
  }

  & .focus {
    border: 2px green solid;
  }

  .video {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    ::v-deep .dplayer-menu {
      > :nth-last-child(-n + 3) {
        display: none;
      }
    }
  }
  .hideMenu {
    ::v-deep .dplayer-live-badge,
    ::v-deep .dplayer-controller-mask,
    ::v-deep .dplayer-controller {
      display: none;
    }
  }

  .display-scale {
    ::v-deep .dplayer-video-wrap {
      display: flex;
      justify-content: center;
      align-items: center;

      .dplayer-video {
        object-fit: fill;
      }
    }
  }

  .controlColumn {
    position: absolute;
    // height: 40px;
    width: 100%;
    color: #fff;
    // background: red;
    background-image: linear-gradient(
      rgba($color: #111, $alpha: 0.2),
      rgba($color: #000, $alpha: 0.7)
    );
    transition: bottom, opacity, 0.5s;
    .progress {
      padding: 0 10px;
    }
    .fun {
      display: flex;
      justify-content: space-between;
      width: 100%;
      position: absolute;
      i {
        width: 20px;
        height: 20px;
        margin: 10px;
        display: inline-block;
      }
      .left {
        display: flex;

        .text {
          height: 100%;
          line-height: 35px;
          padding-left: 8px;
        }
      }

      .right {
        display: flex;

        .volume {
          position: relative;

          .slider {
            width: 30px;
            height: 0;
            opacity: 0;
            overflow: hidden;
            position: absolute;
            top: 0;
            background: rgba($color: #444, $alpha: 0.5);
            transition: all 0.5s;
            padding-top: 10px;

            ::v-deep .el-slider__runway,
            ::v-deep .el-slider__runway,
            ::v-deep .el-slider__bar {
              height: 2px;
              width: 2px;
            }
            ::v-deep .el-slider__runway {
              margin: 0 14px;
            }
            ::v-deep .el-slider__button {
              width: 10px;
              height: 10px;
              background-color: #eee;
              border: 0px;
            }
            ::v-deep .el-slider__button-wrapper {
              // top: -16px
              left: -17px;
            }
          }

          &:hover {
            .slider {
              height: 100px;
              top: -100px;
              opacity: 1;
            }
          }
        }

        .times {
          height: 40px;
          line-height: 38px;
          padding: 0 5px 0 0;
          width: 45px;
          text-align: center;

          .select {
            width: 80px;
            height: 0;
            opacity: 0;
            overflow: hidden;
            position: absolute;
            transform: translateX(-25px);
            top: 0;
            background: rgba($color: #444, $alpha: 0.5);
            transition: all 0.5s;
            padding: 0px;
            text-align: center;
            line-height: 30px;

            .timesItem {
              padding: 0;
              margin: 0;
              &:hover {
                background-color: #414141;
              }
            }
          }

          &:hover {
            .select {
              height: 210px;
              top: -210px;
              opacity: 1;
            }
          }
        }
      }
    }
  }
}
.full-screen {
  height: 100vh;
  width: 100vw;
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
